<!--
 * @Description:
 * @version:
 * @Author: sunqian_sr
 * @Date: 2022-12-01 18:23:22
 * @LastEditors: Andy
 * @LastEditTime: 2023-03-28 19:36:04
-->
<template>
  <!-- 子页面面板 -->
  <x-sub-page class="role-auth" :content="'分配菜单'" @goBack="handleBack" :isFixBtn="true">
    <div style="height: 100%">
      <el-card class="box-card assign-panel" style="height: 100%">
        <div slot="header" class="clearfix">
          <span>租户名称:{{ params?.tenantName ?? '' }}</span>
        </div>
        <div class="flex-row">
          <label class="form-label">所属端:</label>
          <x-radio-group :list-data="clientOptions" :prop-object="clientProps" v-model="checkVal" />
        </div>
        <el-scrollbar
          class="menu-content x-tree-container"
          v-loading="loading"
          :element-loading-text="$t('common.loading')"
          element-loading-spinner="el-icon-loading"
        >
          <!-- <MenueItem :treeData="menuData" :default-props="defaultProps"></MenueItem> -->
          <el-tree
            :data="menuData"
            show-checkbox
            ref="menuTree"
            node-key="id"
            :highlight-current="false"
            :expand-on-click-node="false"
            default-expand-all
            :render-content="renderContent"
            @check="handleCheckChange"
            :props="defaultProps"
          >
          </el-tree>
        </el-scrollbar>
      </el-card>
    </div>
    <fixed-btn-area>
      <el-button type="primary" @click="handleSubmit" :loading="submitLoading"> 保存 </el-button>
      <el-button @click="handleBack"> 取消 </el-button>
    </fixed-btn-area>
  </x-sub-page>
</template>
<script lang="jsx">
  import { throttle } from '@package/utils'
  import { apiGetMenuTree, apiPostApplication } from '@/modules/auth/api'
  import MenueItem from './menueTree.vue'
  import { menuTenantAdd, menuTenant } from '../api/tenant.js'
  import { EnumApiCode } from '../../../../../../globalEnum.js'
  // import { menuTenantAdd } from '../api/tenant.js'
  export default {
    name: 'AssignMenu',
    components: { MenueItem },
    inject: ['closePages'],
    data() {
      return {
        menuData: [],
        // defaultProps: {
        //   label: '',
        //   value: ''
        // },
        defaultProps: {
          label: 'menuName',
          children: 'children'
        },
        // menuPms: [],
        // menuPmsProps: {
        //   children: 'children',
        //   label: 'name'
        // },
        dataPms: [],
        dataPmsProps: {
          children: 'children',
          label: 'name'
        },
        loading: false,
        submitLoading: false,
        expandedKeys: [],
        params: {},
        clientOptions: [],
        checkVal: '',
        clientProps: {
          label: 'clientName',
          value: 'clientId'
        }
        // activeName:'first'
      }
    },
    watch: {
      checkVal: {
        handler(val) {
          if (this.checkVal) {
            this.getMenuTenant()
          }
        },
        immediate: true,
        deep: true
      }
    },
    mounted() {
      // 这边回填菜单权限和数据权限数据
      this.params = JSON.parse(this.$route.query.param)
      this.initClientOptions()
      // this.getMenuTenant()
    },
    methods: {
      initClientOptions() {
        apiPostApplication({ data: {}, pageNum: 1, pageSize: 10 }).then(({ code, data }) => {
          if (code === EnumApiCode.Success) {
            this.clientOptions = data.list
            if (!this.checkVal) {
              this.checkVal = 'srm-manage'
            }
          }
        })
      },
      handleCancel() {
        this.$router.go(-1)
        this.closePages()
      },
      handleSubmit: throttle(function () {
        this.submitLoading = true
        const checkedKeys = this.$refs.menuTree.getCheckedKeys()
        const halfCheckedKeys = this.$refs.menuTree.getHalfCheckedKeys()
        const param = {
          menuIds: [...checkedKeys, ...halfCheckedKeys],
          tenantId: this.params?.id ?? ''
        }
        menuTenantAdd(param).then(
          (res) => {
            this.submitLoading = false
            if (res.code === EnumApiCode.Success) {
              this.$message.success(this.$t('common.opeartionSuccess'))
            } else {
              this.$message.error(res.msg)
            }
          },
          () => {
            this.submitLoading = false
          }
        )
      }, 1000),
      handleBack() {
        this.$router.go(-1)
        this.closePages()
      },
      renderContent(h, { node, data, store }) {
        // 树节点的内容区的渲染 Function
        let classname = ''
        let iconClass = ''
        // 由于项目中有三级菜单也有四级级菜单，就要在此做出判断
        if (`${data.menuType}` === '3') {
          classname = 'flex-node'
        } else {
          iconClass = 'iconfont icon-erjicaidan'
        }

        return (
          <div class={classname}>
            <i class={iconClass} />
            {node.label}
          </div>
        )
      },
      handleCheckChange() {
        this.handleSetClass()
      },
      handleSetClass() {
        this.$nextTick(() => {
          const btnNodes = document.getElementsByClassName('flex-node')
          for (let i = 0; i < btnNodes.length; i++) {
            btnNodes[i].parentNode.parentNode.parentNode.style.display = 'flex'
            btnNodes[i].parentNode.parentNode.parentNode.style.flexFlow = 'wrap'

            if (btnNodes[i].parentNode.parentNode.classList) {
              btnNodes[i].parentNode.parentNode.classList.add('btn-node')
            }
            // btnNodes[i].parentNode.onmouseover = function () {
            //   this.style.backgroundColor = '#fff'
            // }
            // const childrenNodes = btnNodes[i].parentNode.parentNode.parentNode.children
            // let isNum = 0
            // for (let j = 0; j < childrenNodes.length; j++) {
            //   if (childrenNodes[j].classList.value.indexOf('btn-node') !== -1) {
            //     childrenNodes[j].classList.remove('block-node')
            //     isNum++
            //   } else {
            //     childrenNodes[j].classList.add('block-node')
            //   }
            //   if (isNum > 1) {
            //     // console.log(childrenNodes[j], 'ppppppp')
            //     childrenNodes[j].classList.add('no-line')
            //   }
            // }
          }
          const menuNodes = document.getElementsByClassName('menu-node')
          for (let j = 0; j < menuNodes.length; j++) {
            menuNodes[j].parentNode.parentNode.style.flexBasis = '100%'
          }
        })
      },
      getTreeCheckbox(datas) {
        // 遍历树  获取id数组
        for (const i in datas) {
          if (datas[i].isCheckBox) {
            const item = {
              menuId: datas[i].id,
              tenantId: this.param.id
            }
            //  this.expandedKeys.push(datas[i].id) // 遍历项目满足条件后的操作
            this.expandedKeys.push(item) // 遍历项目满足条件后的操作
          }
          if (datas[i].children) {
            // 存在子节点就递归
            this.getTreeCheckbox(datas[i].children)
          }
        }
      },
      getMenuTenant() {
        this.loading = true
        apiGetMenuTree({ clientId: this.checkVal })
          .then(({ data }) => {
            this.loading = false
            this.menuData = data
            const result = this.filterTreeData([...this.params.menus], this.menuData)
            this.$nextTick(() => {
              this.$refs.menuTree.setCheckedKeys(result)
              this.handleSetClass()
            })
          })
          .catch(() => {
            this.loading = false
          })
      },
      filterTreeData(checkedKeys, menus) {
        menus.forEach((item) => {
          if (checkedKeys.includes(item.id) && item.children.length) {
            checkedKeys.splice(checkedKeys.indexOf(item.id), 1)
          }
          if (item.children.length) {
            checkedKeys = this.filterTreeData(checkedKeys, item.children)
          }
        })
        return checkedKeys
      }
      // handleClick(tab){
      //   this.activeName = tab.name
      // }
    }
  }
</script>

<style lang="scss" scoped>
  .title {
    font-size: 16px;
    line-height: 40px;
    box-sizing: border-box;
    width: 100px;
    margin-bottom: 16px;
    padding: 10px 15px;
    text-align: right;
    color: #606266;
  }

  .role-auth {
    // background-color: #fff;
  }

  .menu-tree,
  .data-tree {
    min-height: 200px;
    margin: 15px;
    border: 1px solid #e0e0e0;
  }

  .menu-content {
    height: calc(100% - 60px);
  }

  i.iconfont.icon-erjicaidan {
    font-size: 14px;
  }
  .form-label {
    line-height: 30px;
    margin-right: 16px;
    white-space: nowrap;
    color: #424242;
    padding-left: 23px;
  }
</style>
<style lang="scss">
  @import '../../../common/assets/style/tree';
  /* element滚动条组件 隐藏水平滚动条 */

  .menu-content .el-scrollbar__wrap {
    overflow-x: hidden;
    background-color: #fff;
  }

  .is-horizontal {
    display: none;
  }

  .assign-panel .el-card__body {
    height: calc(100% - 50px);
  }
  .menu-content .el-scrollbar__view {
    height: 100%;
  }
  .menu-content .el-tree {
    height: 100%;
  }
</style>
